package com.ruoyi.common.utils;

import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Workbook;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 导出工具类
 * 
 * @author Administrator
 *
 */
public class ExportUtil {

	/**
	 * 向excel插入图片
	 * 
	 * @param imgPath
	 * @param workbook
	 * @param col1
	 * @param row1
	 * @param col2
	 * @param row2
	 */
	public static void createPicture(String imgPath, Workbook workbook, String sheet, short col1, int row1, short col2, int row2) {
		BufferedImage bufferImg = null;
		// 先把读进来的图片放到一个ByteArrayOutputStream中，以便产生ByteArray
		try {
//			File file = new File(imgPath);
			URL url = new URL(imgPath);
			if (url != null) {
				ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
				bufferImg = ImageIO.read(url);
				String fileType = imgPath.substring(imgPath.lastIndexOf(".")+1);
				ImageIO.write(bufferImg, fileType, byteArrayOut);

				/* HSSFWorkbook wb = new HSSFWorkbook(); */
				HSSFSheet sheet1 = (HSSFSheet) workbook.getSheet(sheet);
				// 画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
				HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
				// anchor主要用于设置图片的属性
				HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, col1, row1, col2, row2);
				anchor.setAnchorType(ClientAnchor.AnchorType.byId(3));
				// 插入图片
				patriarch.createPicture(anchor,workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
